<script setup lang="ts">
import { ref } from 'vue';
import { getYear } from '@/hooks/useDate';
import { titleList } from '@/hooks/useCommon';
import { getClass, getFillDesc, getSumColumns, getSummaries,useTableHeight } from '@/hooks/useMethod';

import { FillDTO } from '@/api/fill/business/Types';
import { getList, saveIssue, updateStatus } from '@/api/fill/issue/manage-two';
import { getBudgetDeptList } from '@/api/fill/issue/business-two';
import InputWithPopover from '@/components/InputWithPopover/index.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(true);
const buttonLoading = ref(false);
const showSearch = ref(true);
const { yard_type } = toRefs<any>(proxy?.useDict('yard_type'));
// 使用示例
const tableStyle = useTableHeight(showSearch);
const deptList = ref<DeptListVO[]>([]);
/*预算部门列表*/
const getDeptList = () => {
  getBudgetDeptList(queryParams.value).then((res) => {
    deptList.value = res.data;
  });
};

const queryFormRef = ref<ElFormInstance>();
// 查询参数
const queryParams = ref<FillDTO>({
  year: getYear(),
  deptCode: undefined,
  issue: undefined,
  type: 2
});

const tableList = ref([]);

//全部列表查询
const getListAll = async () => {
  if (!queryParams.value.deptCode) {
    proxy.$modal.msgError('请选择预算部门');
    return;
  }
  if (!queryParams.value.year) {
    proxy.$modal.msgError('请选择年份');
    return;
  }
  loading.value = true;
  getList(queryParams.value)
    .then((res) => {
      tableList.value = res.data;
    })
    .finally(() => {
      loading.value = false;
    });
};

/** 搜索按钮操作 */
const handleQuery = () => {
  getListAll();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.value = {
    year: getYear(),
    deptCode: undefined,
    issue: undefined, //当前流程的主表id
    type: 1
  };
  tableList.value = [];
};

/*下达数据记录*/
const issueDTO = ref({
  year: undefined,
  deptCode: undefined,
  deptName: undefined,
  issueData: []
});

/*赋值*/
const assign = () => {
  issueDTO.value.year = queryParams.value.year;
  issueDTO.value.deptCode = queryParams.value.deptCode;
  issueDTO.value.issueData = tableList.value;
};
/*按钮显示状态/编辑状态*/
const drop = ref(false);
/*压降*/
const handleDrop = () => {
  if (!queryParams.value.deptCode) {
    proxy.$modal.msgError('请选择预算部门');
    return;
  }
  if (!queryParams.value.year) {
    proxy.$modal.msgError('请选择年份');
    return;
  }
  assign();
  if (queryParams.value.issue === 2) {
    proxy.$modal.msgWarning(issueDTO.value.year + '年' + issueDTO.value.deptName + '业务预算下达已完成');
    return;
  }

  console.log('data:', tableList.value);
  if (tableList.value.length <= 0) {
    proxy.$modal.msgWarning('该部门数据暂无数据');
    return;
  }
  if (queryParams.value.issue === 2) {
    proxy.$modal.msgWarning(issueDTO.value.year + '年' + issueDTO.value.deptName + '下达已完成');
    return;
  }
  buttonLoading.value = false;
  buttonLoading.value = true;
  loading.value = true;
  /*保存数据*/
  if (drop.value) {
    saveIssue(issueDTO.value)
      .then((res) => {
        if (res.data) {
          proxy.$modal.msgSuccess('操作成功');
          getDeptList();
        }
        getListAll();
        queryParams.value.issue = 1;
      })
      .finally(() => {
        loading.value = false;
        buttonLoading.value = false;
      });
  }
  drop.value = !drop.value;
};
/*下达*/
const issue = () => {
  if (!queryParams.value.deptCode) {
    proxy.$modal.msgError('请选择预算部门');
    return;
  }
  if (!queryParams.value.year) {
    proxy.$modal.msgError('请选择年份');
    return;
  }
  assign();
  if (queryParams.value.issue === 2) {
    proxy.$modal.msgWarning(issueDTO.value.year + '年' + issueDTO.value.deptName + '管理科目预算下达已完成');
    return;
  }
  proxy.$modal.confirm('是否确认下达？').then(() => {
    if (tableList.value.length <= 0) {
      proxy.$modal.msgWarning('该部门数据暂无数据');
      return;
    }
    loading.value = true;
    buttonLoading.value = true;
    updateStatus(issueDTO.value)
      .then((res) => {
        if (res.data) {
          proxy.$modal.msgSuccess('操作成功');
          getDeptList();
          queryParams.value.issue = 2;
          drop.value = false;
        }
        getListAll();
      })
      .finally(() => {
        loading.value = false;
        buttonLoading.value = false;
      });
  });
};

/*查询*/
const queryData = (value: any) => {
  const dept = deptList.value.find((item) => item.deptCode === value);
  queryParams.value.issue = dept.issue;
  issueDTO.value.deptName = dept.deptName;
  getListAll();
};

onMounted(() => {
  getDeptList();
});

// 获取计算列（使用computed保持响应式）
const sumColumns = computed(() => getSumColumns(yard_type.value, titleList));

// 在表格中使用
const tableSummaries = (param: any) => {
  return getSummaries(param, sumColumns.value);
};
</script>

<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="never">
          <el-form ref="queryFormRef" :inline="true">
            <el-form-item label="年份" prop="year">
              <el-date-picker type="year" format="YYYY" value-format="YYYY" v-model="queryParams.year" @change="getDeptList" />
            </el-form-item>
            <el-form-item label="预算部门" prop="deptCode">
              <el-select
                v-model="queryParams.deptCode"
                placeholder="请选择预算部门"
                @change="queryData"
                clearable
                filterable
                collapse-tags
                collapse-tags-tooltip
              >
                <el-option
                  v-for="item in deptList"
                  :key="item.deptCode"
                  :label="item.deptName + (' (' + (item.issue === 2 ? '已下达' : '未下达') + ')')"
                  :value="item.deptCode"
                  :class="getClass(item.issue)"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <div style="display: flex; justify-content: space-between">
          <div>
            <el-button
              :type="!drop ? 'danger' : 'primary'"
              plain
              v-hasPermi="['issue:manageTwo:save']"
              @click="handleDrop"
              v-if="queryParams.issue != 2"
            >
              <svg-icon icon-class="down-fill" v-if="!drop" />
              <svg-icon icon-class="save-issue" v-else />

              <span style="margin-left: 5px">{{ drop ? '保存' : '压降' }}</span>
            </el-button>
            <el-button type="success" plain icon="Position" @click="issue" v-hasPermi="['issue:manageTwo:issue']" v-if="queryParams.issue === 1">
              下达
            </el-button>
          </div>
          <div>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getListAll" />
          </div>
        </div>
      </template>
      <div class="table-class">
        <el-table
          ref="tableRef"
          :data="tableList"
          :show-summary="true"
          :summary-method="tableSummaries"
          :style="tableStyle"
          append
          :loading="loading"
          class="custom-table enhanced-table"
        >
          <el-table-column prop="subjectCode" label="预算科目编码" v-if="false" align="center" />
          <el-table-column prop="subjectName" label="预算科目名称" width="220" align="center" fixed="left">
            <template #default="scope">
              <span v-if="scope.row.isPercentage" style="color: #ff1493">{{ scope.row.subjectName }}</span>
              <span v-else>{{ scope.row.subjectName }}</span>
            </template>
          </el-table-column>
          <el-table-column v-for="item in titleList" :key="item.key" :label="item.label" align="center">
            <el-table-column
              v-for="dict in yard_type"
              :key="dict.value"
              :label="dict.label"
              :prop="dict.value + '_' + item.key"
              align="center"
              show-overflow-tooltip
              width="170"
            >
              <template #default="scope">
                <InputWithPopover
                  v-model="scope.row[dict.value + '_' + item.key]"
                  :drop="drop"
                  :fill-desc="getFillDesc(scope.row, dict.value, item.key)"
                />
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="合计" align="center">
            <el-table-column
              v-for="dict in yard_type"
              :key="dict.value"
              :label="dict.label"
              :prop="dict.value + '_total'"
              align="center"
              show-overflow-tooltip
              width="170"
            >
            </el-table-column>
            <el-table-column align="center" label="总合计" prop="total" show-overflow-tooltip width="170"></el-table-column>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
  </div>
</template>

<style scoped lang="scss">
@import '@/assets/styles/common-style';
</style>
